package me.numark.activities;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.numark.MainActivity;
import me.numark.R;
import me.numark.model.User;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.Settings;
import me.numark.utils.Utils;
import me.numark.view.CircleImageView;

/**
 * Created by Evan on 15/8/1.
 */
public class AccountsActivity extends BaseActivity implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {

    @Bind(R.id.list)
    ListView mList;
    String[] uids;
    HashMap<String, User> userHashMap = new HashMap<>();
    UserAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_accounts;
        super.onCreate(savedInstanceState);
        titleTextView.setText(R.string.setting_accounts);
        mAdapter = new UserAdapter();
        mList.setAdapter(mAdapter);
        mList.setOnItemClickListener(this);
        mList.setOnItemLongClickListener(this);
        reloadData();
        LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
                new IntentFilter(Constants.ACTION_USER_CHANGED));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
    }

    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Constants.ACTION_USER_CHANGED.equals(intent.getAction())) {
                reloadData();
            }
        }
    };

    void reloadData() {
        uids = Settings.getUids();
        for (String uid : uids) {
            if (!userHashMap.containsKey(uid)) {
                User user = Settings.getUser(uid);
                userHashMap.put(uid, user);
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == uids.length) {
            startActivity(new Intent(this, LogInActivity.class));
            return;
        }
        int uid = (int) id;
        if (uid != 0) {
            Settings.setCurrentUid(uid);
            Global.currentUser = userHashMap.get(String.valueOf(uid));
            LocalBroadcastManager.getInstance(getBaseContext())
                    .sendBroadcast(new Intent(Constants.ACTION_USER_CHANGED));

            startActivity(new Intent(AccountsActivity.this,MainActivity.class));
            this.finish();
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        final int uid = (int) id;
        if (uid == Global.getCurrentUid()) {
            Utils.showSnackbar(rootView, R.string.not_remove_currentuser);
            return true;
        }
        new AlertDialog.Builder(this)
                .setMessage(R.string.dialog_del_account)
                .setNegativeButton(android.R.string.cancel, null)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Settings.delUser(String.valueOf(uid));
                        reloadData();
                    }
                })
                .show();
        return true;
    }

    class UserAdapter extends BaseAdapter {
        public UserAdapter() {
        }

        @Override
        public int getCount() {
            if (uids == null)
                return 1;
            return uids.length + 1;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public Object getItem(int position) {
            if (uids == null || position == uids.length)
                return null;
            String uid = uids[position];
            return userHashMap.get(uid);
        }

        @Override
        public long getItemId(int position) {
            if (uids == null || position == uids.length)
                return 0;
            String uid = uids[position];
            return Integer.parseInt(uid);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                v = getLayoutInflater().inflate(R.layout.account_list_item, parent, false);
                v.setTag(new UserViewHolder(v));
            }
            UserViewHolder holder = (UserViewHolder) v.getTag();
            User user = (User) getItem(position);
            if (user != null) {
                holder.avatar.setBorderColor(Global.avatarColor);
                holder.avatar.setBorderWidth(2);
                if (user.pic != null) {
                    Picasso.with(AccountsActivity.this).load(user.pic).into(holder.avatar);
                }else {
                    holder.avatar.setImageResource(R.drawable.avatar_bg_normal);
                }
                holder.name.setText(user.nick);
                holder.checkbox.setVisibility(user.uid == Global.getCurrentUid() ? View.VISIBLE : View.INVISIBLE);
            } else {
                /*holder.avatar.setImageResource(R.drawable.add_account);
                holder.name.setText(R.string.add_account);
                holder.checkbox.setVisibility(View.INVISIBLE);*/
                holder.accountButton.setVisibility(View.VISIBLE);
                holder.devider.setVisibility(View.GONE);
                holder.accountButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(AccountsActivity.this, LogInActivity.class));

                    }
                });
            }
            return v;
        }
    }

    class UserViewHolder {
        @Bind(R.id.avatar)
        CircleImageView avatar;

        @Bind(R.id.checkbox)
        ImageView checkbox;

        @Bind(R.id.name)
        TextView name;

        @Bind(R.id.account_button)
        Button accountButton;

        @Bind(R.id.account_devider)
        View devider;

        public UserViewHolder(View v) {
            ButterKnife.bind(this, v);
        }
    }
}
